import * as vscode from "vscode";
import * as path from "path";
import * as fs from 'fs';
import {setStoreJson,getStoreJson} from "../util/store";
import {getConfiguration} from "../util/util";
import {Novels,Chapter} from "../@types/index";
const ejs = require('ejs');


class DetailProvider {
    public readonly viewType = 'webview-panel';

    public novels!: Novels; //小说信息
    public chapterList:Chapter[] = []; //小说章节
    public activeChapter!:Chapter; //当前章节
    public activeChapterIndex:number = 0; //当前章节索引
    public activeChapterTitle:string = ""; //当前章节标题
    public defaultTemplate:string= ""; //默认模板
    public contentSetting:string = ``; // 内容样式设置
    private webviewPanel!: vscode.WebviewPanel|null; //webview面板
    private context:vscode.ExtensionContext; //上下文
    public sidebarProvider:any; //侧边面板实例

    constructor(context:vscode.ExtensionContext,sidebarProvider:any){
        this.context = context;
        this.sidebarProvider = sidebarProvider;
        this.contentSetting = this.getContentSetting();
    }


    /**
     * 展示面板
     * @param novels 
     */
    public showWebviewPanel(novels:Novels){
        if(!this.novels  || this.novels.id !== novels.id){
            this.novels = novels;
            this.chapterList = [];
        }
        this.activeChapterIndex = novels.activeChapterIndex ? novels.activeChapterIndex : 0;
        this.activeChapterTitle = novels.activeChapterTitle;
        this.refreshWebviewView();
    }

    /**
     * 创建webview面板
     * @returns 
     */
    public resolveWebviewContent (){
        if(this.webviewPanel){
            return this.webviewPanel;
        };
        this.webviewPanel = vscode.window.createWebviewPanel(
            this.viewType,
            "",
            vscode.ViewColumn.Active, ////column || vscode.ViewColumn.One,
            {
                enableScripts: true,
                enableCommandUris: true,
                enableFindWidget: true,
                retainContextWhenHidden: true,
            }
        );
        this.webviewPanel.onDidDispose(
            () => {
                this.webviewPanel = null;
            },
            undefined,
            this.context.subscriptions
        );
       
        this.webviewPanel.webview.onDidReceiveMessage(this.onDidReceiveMessage, this,this.context.subscriptions);
        return this.webviewPanel;
    }

    /**
     * 加载webview内容
     */
    public async refreshWebviewView (){
        if(!this.webviewPanel){
            this.webviewPanel = this.resolveWebviewContent();
        }
        let data = await this.getChapterData();
        let html = this.getTemplate();
        
        if(data){
            this.webviewPanel.title = this.activeChapterTitle;
            this.webviewPanel.webview.html = ejs.render(html, data);
        }else{
            vscode.window.showInformationMessage('书籍打开错误！');
        }
    }

    /**
     * 将系统样式设置参数拼接成字符串
     * @returns 
     */
    public getContentSetting () {
        let config:any = getConfiguration();
        let style = "";
        if(config.backgroundColor){
            style += `background-color:${config.backgroundColor};`;
        }
        if(config.fontSize){
            style += `font-size:${config.fontSize}px;`;
        }
        if(config.fontColor){
            style += `color:${config.fontColor};`;
        }
        if(config.lineHeight){
            style += `line-height:${config.lineHeight}px;`;
        }
        return style;
    }

    /**
     * 获取基础模板
     * @returns 
     */
    public getTemplate(){
        if(this.defaultTemplate) {
            return this.defaultTemplate;
        }
        let tplPath = path.join(this.context.extensionPath, path.join('static', 'template', 'detail.html'));
       
        let html = fs.readFileSync(tplPath, 'utf-8');
        html =  html.replace(/(@)(.+?)"/g, (m:any, $1:any, $2:any) => {
            const resourcePath = vscode.Uri.joinPath(this.context.extensionUri, 'static', $2);
            const resourceSrc = this.webviewPanel ? this.webviewPanel.webview.asWebviewUri(resourcePath) : '"';
            return resourceSrc + '"';
        });
        this.defaultTemplate = html;
        return html;
    }

    /**
     * 获取章节数据
     * @returns 
     */
    public async getChapterData() {
        if(!this.novels){
            vscode.window.showInformationMessage('书籍打开错误！');
            return null;
        };
        //获取目录文件
        if(!this.chapterList.length){
            this.chapterList = await getStoreJson(this.context.globalStorageUri,"novels_chapter_"+this.novels.id);
        }
        if(this.chapterList[this.activeChapterIndex]){
            this.activeChapter = this.chapterList[this.activeChapterIndex];
            this.activeChapterTitle = this.activeChapter.title;
            let filePath = vscode.Uri.file(this.activeChapter.filePath);
            //获取章节文本并且按换行分割
            const content = fs.readFileSync(filePath.fsPath, 'utf-8');
            const contentList = content.split(/\r\n|\r|\n/).map((item:string) => {
                return item ? item.trim() : "";
            })
            return {
                novels:this.novels,
                contentList :contentList,
                chapterList:this.chapterList,
                activeChapterIndex:this.activeChapterIndex,
                activeChapterTitle:this.activeChapterTitle,
                contentSetting:this.contentSetting
            }
        }
        vscode.window.showInformationMessage('书籍打开错误！');
        return null;
    }

    /**
     * 监控webview消息
     * @param data 
     */
    async onDidReceiveMessage(data:any){
        switch (data.command) {
            case "message" :{ //页面消息返回
                vscode.window.showInformationMessage(data.data);
                break;
            }
            case "prevChapter":{ //上一章
                this.prevChapter();
                break;
            }
            case "nextChapter":{ //下一章
                this.nextChapter();
                break;
            }
            case "specify":{ //跳转章节
                this.switchChapters(data.data);
                break;
            }
            case "close":{ //关闭面板
                this.disposeWebviewPanel();
                break;
            }
            case "hidden":{ //摸鱼
                if(data.data === 'hide'){
                    if(this.webviewPanel){
                        this.webviewPanel.title = "Untitled-1";
                    }
                }else{
                    if(this.webviewPanel){
                        this.webviewPanel.title = this.activeChapterTitle;
                    }
                }
            }
        }
    }

    /**
     *上一章 
     */
    public async prevChapter () {
        if(this.activeChapterIndex > 0){
            this.switchChapters(this.activeChapterIndex - 1);
        }
    }

    /**
     * 下一章
     */
    public nextChapter () {
        if(this.activeChapterIndex < (this.novels.chapterLength-1)){
            this.switchChapters(this.activeChapterIndex + 1);
        }
    }

    /**
     * 关闭面板
     */
    public disposeWebviewPanel () {
        this.webviewPanel?.dispose();
    }

    /**
     * 跳转章节
     * @param index 
     */
    public async switchChapters(index:number){
        this.activeChapterIndex = index;
        await this.refreshWebviewView();
        this.novels.activeChapterIndex = this.activeChapterIndex;
        this.novels.activeChapterTitle = this.activeChapterTitle;
        let novelsList =  await getStoreJson(this.context.globalStorageUri,"novels_list");
        novelsList.forEach((item:any) => {
            if(item.id === this.novels.id){
                item.activeChapterIndex = this.activeChapterIndex;
                item.activeChapterTitle = this.activeChapterTitle;
            }
        });
        await setStoreJson(this.context.globalStorageUri,"novels_list",novelsList);
        this.sidebarProvider.refreshWebviewView(novelsList);
    }

}

export default DetailProvider;


